/**
 * 
 */
package com.android.dwt.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.dwt.Position;
import com.android.dwt.R;
import com.android.dwt.TaskItem;
import com.android.dwt.R.drawable;
import com.android.dwt.R.id;
import com.android.dwt.R.layout;
import com.android.dwt.R.string;
import com.android.dwt.data.GTDApp;
import com.android.dwt.service.DWTService;
import com.android.dwt.service.DWTService.MyBinder;
import com.android.dwt.util.C;
import com.android.dwt.util.TaskUtil;
import com.android.dwt.util.Utils;

/**
 * @author xlees
 * 
 */
public class NewTaskAct extends Activity
		implements OnClickListener, OnDateSetListener, OnTimeSetListener,
		ServiceConnection, TextWatcher {
	
	private final String TAG = "NewTaskAct";
	public static final int RESULT_TAG = 2;
	public static final int RESULT_REMIND = 5;
	private final int DATE_DIALOG = 1;  
    private final int TIME_DIALOG = 2;
    private final int DLG_REMIND_TIME = 3;
    private final int DLG_REMIND = 4;

	private GTDApp ga;
	private int contextPos = 0;
	private int projectPos = 0;
	private int positionPos = 0;
	private ArrayList<Integer> mTags = new ArrayList<Integer>();
	private TextView currentView;
//	private int repeatId;
	private int priorPos = 0;		// no priority
	private int mListIndex = 0;		// inbox default
	private boolean mIsAgenda = false;
	private View mAgenda;
	private boolean isEdit;	// edit task or create a new task
	private int mCalType = -1;		
	private int mNumOfTasks = 1;
	private int mRepeatType = 0;		// repeat type
	private Intent mIntent;
	private long mRowId;
	private TaskItem mNewTask;
	private ArrayList<Long> mID = new ArrayList<Long>();
	private ArrayList<Calendar> mRmd = new ArrayList<Calendar>();
	private Calendar mOldRemind;		// for edit task, no remind time if null.
	
	private DWTService mService;
	private boolean mBound;
	
	private Calendar calStart;
	private Calendar calEnd;
//	private Calendar mCldRepeat;
	private Calendar mCldRemind;
	private SimpleDateFormat mSdfDate = new SimpleDateFormat("yyyy-MM-dd");
	private SimpleDateFormat mSdfTime = new SimpleDateFormat("HH:mm");
	private SimpleDateFormat mSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	private EditText et_task;
	private EditText et_note;
	private LinearLayout ll_list;
	private LinearLayout ll_repeat;
	private LinearLayout ll_remind;
	private LinearLayout ll_prior;
	private TextView start_date, start_time;
	private TextView end_date, end_time;
	public HashMap<Integer, String> mHmPre = new HashMap<Integer, String>();
	private CheckBox cb_day;
	private int taskStatus;
	protected int mPeriod;
	private int mPosIndex = 0;
	private int mRemindIndex = -1;
	
	private boolean mTimeRemind;		// remind is set or not
	private boolean mLocAlert;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Log.i(TAG, "now onCreate method is called!");

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.new_task);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_task);
		
		ga = (GTDApp) getApplication();
		
		calStart = Calendar.getInstance();
		calEnd = Calendar.getInstance();
		mCldRemind = Calendar.getInstance();
		
		mAgenda = getLayoutInflater().inflate(R.layout.agenda_added, null);
		
		initViews();
		
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		lp.setMargins(10, 10, 10, 0);
		
		mIntent = getIntent();
		if (mIntent.hasExtra("new_task")) {			// new task
			
			taskStatus = mIntent.getIntExtra("task_status", C.TASK.UNCOMPLETED);
			mListIndex = mIntent.getIntExtra("list_index", -1);
			((TextView) findViewById(R.id.tv_list)).setText(
					(String) ga.lists.get(mListIndex).get("item_name"));
			
			if (mListIndex == GTDApp.AGENDA) {
				
				LinearLayout sv = (LinearLayout) findViewById(R.id.ll_in_scroll);
				sv.addView(mAgenda, 2, lp);

		        mIsAgenda = true;
			}
			
			if (mIsAgenda)
				initAgenda();
			
		} else {		// edit an existing task
			
			isEdit = true;
			((TextView) findViewById(R.id.tv_task_title))
				.setText(getString(R.string.edit_task_title));
			
			mRowId = mIntent.getLongExtra("row_id", -1);			Log.e(TAG, "passed id: "+mRowId);
			TaskItem task = ga.getDbta().getTaskItem(mRowId);
//			TaskItem task = (TaskItem) mIntent.getSerializableExtra("task_data");
//			mListIndex = mIntent.getIntExtra("list_index", -1);
			mListIndex = TaskUtil.getListIndex(ga.mList, task.getListName());
			
			String place = task.getPosition();
			mPosIndex = findPalceIndex(place);
			
//			if (ga.lists.indexOf(task.getListName()) == GTDApp.AGENDA) {		// agenda
			if (mListIndex == GTDApp.AGENDA) {
				
				mIsAgenda = true;
				
				LinearLayout sv = (LinearLayout) findViewById(R.id.ll_in_scroll);
				sv.addView(mAgenda, 2, lp);
				
				/*LinearLayout sv = (LinearLayout) findViewById(R.id.ll_in_scroll);
		        LinearLayout ll_agd = (LinearLayout) mAgenda.findViewById(R.id.ll_agd);
		        sv.addView(ll_agd, 2);*/
			}
			
			if (mIsAgenda)
				initAgenda();
			
			fillTaskData(task);
			((Button) findViewById(R.id.btn_save_task)).setEnabled(true);
		}
		
		handleEvent();

	}
	
	private int findPalceIndex(String place) {
		
		int index = -1;
		
		ArrayList<Position> loc = ga.getPositions();
		for (int i=0; i<loc.size(); i++) {
			
			if (loc.get(i).getPlace().equals(place)) {
				
				index = i;
				break;
			}
			
		}
		
		if (index == -1) {
			
			Log.e(TAG, "not find this place in location list!");
		}
		
		return index;
	}
	
	private void initViews() {
		
		et_task = (EditText) findViewById(R.id.et_task);
		et_task.clearFocus();
		
		et_note = (EditText) findViewById(R.id.et_note);
		
		ll_list = (LinearLayout) findViewById(R.id.ll_list);
		
		ll_remind = (LinearLayout) findViewById(R.id.ll_remind);
		
		ll_prior = (LinearLayout) findViewById(R.id.ll_prior);
		((TextView) findViewById(R.id.tv_prior)).setText(getString(R.string.prior_none));
	}
	
	// fill previous task data into each view if there is task data
	private void fillTaskData(TaskItem task) {
		
		et_task.setText(task.getTaskName());
		et_note.setText(task.getTaskNote());
		((TextView) findViewById(R.id.tv_list)).setText(task.getListName());
		
		
		String context = task.getContext();
		if (context.equals(ga.getContexts().get(0))) {	// no context
			
			((TextView) findViewById(R.id.tv_context)).setText("");
			
		} else {
			
			((TextView) findViewById(R.id.tv_context)).setText(context);
		}
		
		String project = task.getProject();
		if (project.equals(ga.getProjects().get(0))) {
			
			((TextView) findViewById(R.id.tv_project)).setText("");
			
		} else {
			
			((TextView) findViewById(R.id.tv_project)).setText(project);
		}
		
		String pos = task.getPosition();		Log.e(TAG, "position: "+pos);
		if (pos.equals(ga.getPositions().get(0).getPlace())) {
			
			((TextView) findViewById(R.id.tv_position)).setText("");
			
		} else {
			
			((TextView) findViewById(R.id.tv_position)).setText(pos);
		}
		
		if ((task.getListName()).equals(getString(R.string.agenda))) {	// this is an agenda
			
//			String date, time;
			Date start = null, end = null;
//			String[] tmp;
			
			Calendar cldStart = Calendar.getInstance();
			Calendar cldEnd = Calendar.getInstance();
			
			try {
				start = mSdf.parse(task.getStartTime());
				end = mSdf.parse(task.getEndTime());
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				
				e.printStackTrace();
			}
			
			cldStart.setTime(start);
			cldEnd.setTime(end);
			
			boolean isAllDay = task.isAllDay();
			cb_day.setChecked(isAllDay);
			
			start_date.setText(mSdfDate.format(cldStart.getTime()));
			end_date.setText(mSdfDate.format(cldEnd.getTime()));
			if (isAllDay) {
				
				start_time.setText("");
				end_time.setText("");
				
			} else {
				
				start_time.setText(mSdfTime.format(cldStart.getTime()));
				end_time.setText(mSdfTime.format(cldEnd.getTime()));
			}
			
			/*if (start.length() > 1) {
				
				tmp = start.split(" ");
				date = tmp[0];
				if (tmp.length > 1) { // date and time
					time = tmp[1];
				} else {	// only the date
					time = "";
				}
				
				start_date.setText(date);
				start_time.setText(time);
				
			} else {
				
				start_date.setText("");
				start_time.setText("");
			}
			
			if (end.length() > 1) {
				
				tmp = end.split(" ");
				date = tmp[0];
				if (tmp.length > 1)
					time = tmp[1];
				else
					time = "";
				
				end_date.setText(date);
				end_time.setText(time);
				
			} else {
				
				end_date.setText("");
				end_time.setText("");
			}*/
			
			((TextView) mAgenda.findViewById(R.id.tv_repeat)).setText(task.getRepeat());
		}
		
		String remind = task.getRemind();
		if (remind.length() > 0) {	// exist remind
			
			try {
				mOldRemind = Calendar.getInstance();
				
				Date date = mSdf.parse(remind);
				mOldRemind.setTime(date);
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				
				e.printStackTrace();
			}
			
		} else {		// no remind time
			
			mOldRemind = null;
		}
		
		((TextView) findViewById(R.id.tv_remind)).setText(remind);
		((TextView) findViewById(R.id.tv_prior)).setText(task.getPrior());
		((TextView) findViewById(R.id.tv_tag)).setText(task.getTags());
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		Log.e(TAG, "now onStart method is called!");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e(TAG, "now onResume method is called!");
		
		/*if (mReceiver == null)
			mReceiver = new MyReceiver();
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(DWTService.ALARMS);
		registerReceiver(mReceiver, intentFilter);*/
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.e(TAG, "now onStop method is called!");

		// savePreferences();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		// ga.close();
		Log.e(TAG, "now onDestroy method is called!");
		super.onDestroy();
		
		if (mBound)
			unbindService(this);
		
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.e(TAG, "now restart method is called!");
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		Log.e(TAG, "now onPause method is called!");
		
		/*if (mReceiver != null)
			unregisterReceiver(mReceiver);*/
	}
	

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		// return super.onCreateDialog(id);
		
		Log.e(TAG, "onCreateDialog is called!!");
		
		Calendar cld = Calendar.getInstance();
		
		Dialog dlg = null;
		switch (id) {
		
			case DATE_DIALOG:
				
				dlg = new DatePickerDialog(this, this,
						cld.get(Calendar.YEAR),
						cld.get(Calendar.MONTH),
						cld.get(Calendar.DAY_OF_MONTH));
				
				break;
				
			case TIME_DIALOG:
				
				dlg = new TimePickerDialog(this, this,
						cld.get(Calendar.HOUR_OF_DAY),
						cld.get(Calendar.MINUTE),
						true);
				
				break;
				
			case DLG_REMIND_TIME:		// all day remind dialog
				
				dlg = new Dialog(this);
				dlg.setContentView(R.layout.date_time);
				dlg.setTitle("设置提醒时间");
				
				LinearLayout ll_remind_date = (LinearLayout) dlg.findViewById(R.id.ll_remind_date);
				ll_remind_date.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						
						showDialog(DATE_DIALOG);
					}
				});
				
				break;
				
			case DLG_REMIND:
				break;
				
			default:
				break;
		}

		return dlg;
	}
	
	@Override
	protected void onPrepareDialog(int id, final Dialog dialog) {
		// TODO Auto-generated method stub
//		super.onPrepareDialog(id, dialog);
		
		Log.i(TAG, "onPrepareDialog is called!");
		
		String strDate, strTime;
//		String[] arrayDate, arrayTime;
		
		Calendar cld = Calendar.getInstance();
		
		switch (id) {
		
			case DATE_DIALOG:
				
				strDate = currentView.getText().toString().trim();
				
				if (strDate.length() > 0) {
					
					Date date = null;
					
					try {
						date = mSdfDate.parse(strDate);
						
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						
						e.printStackTrace();
					}
					
					cld.setTime(date);
					
					/*arrayDate = strDate.split("-");
					int year = Integer.valueOf(arrayDate[0]);
					int month = Integer.valueOf(arrayDate[1]);
					int day = Integer.valueOf(arrayDate[2]);*/
					
					((DatePickerDialog) dialog).updateDate(
							cld.get(Calendar.YEAR),
							cld.get(Calendar.MONTH),
							cld.get(Calendar.DAY_OF_MONTH));
					
				} else {
					
					((DatePickerDialog) dialog).updateDate(cld.get(Calendar.YEAR),
							cld.get(Calendar.MONTH),
							cld.get(Calendar.DAY_OF_MONTH));
				}
				
				break;
				
			case TIME_DIALOG:
				
				strTime = currentView.getText().toString().trim();
				
				if (strTime.length() > 0) {
					
					Date time = null;
					SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
					
					try {
						time = sdf.parse(strTime);
						
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						
						e.printStackTrace();
					}
					
					cld.setTime(time);
					
					/*arrayTime = strTime.split(":");
					int hour = Integer.valueOf(arrayTime[0]);
					int minute = Integer.valueOf(arrayTime[1]);*/
					
					((TimePickerDialog) dialog).updateTime(
							cld.get(Calendar.HOUR_OF_DAY),
							cld.get(Calendar.MINUTE));
					
				} else {
					
					((TimePickerDialog) dialog).updateTime(cld.get(Calendar.HOUR_OF_DAY),
							cld.get(Calendar.MINUTE));
				}
				
				break;
				
			case DLG_REMIND_TIME:
				
				String str = ((TextView) findViewById(R.id.tv_remind)).getText().toString().trim();
				if (str.length() > 0) {
					
					String[] dateTime = str.split(" ");
					((TextView) findViewById(R.id.tv_remind_date)).setText(dateTime[0]);
					((TextView) findViewById(R.id.tv_remind_time)).setText(dateTime[1]);
				}
				
				Button btn_remind_cal = (Button) dialog.findViewById(R.id.btn_remind_cal);
				btn_remind_cal.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
				
				break;
				
			default:
				break;
		}
	}
	
	/*private String format2(int x) {
		String s = "" + x;
		if (s.length() == 1)
			s = "0" + s;
		
		return s;
	}*/
	
	private void initAgenda() {
		
		final Calendar cld = Calendar.getInstance();
		
		cb_day = (CheckBox) mAgenda.findViewById(R.id.cb_day);
		start_date = (TextView) mAgenda.findViewById(R.id.start_date);
		start_time = (TextView) mAgenda.findViewById(R.id.start_time);
		end_date = (TextView) mAgenda.findViewById(R.id.end_date);
		end_time = (TextView) mAgenda.findViewById(R.id.end_time);
		ll_repeat = (LinearLayout) mAgenda.findViewById(R.id.ll_repeat);
		
		if (mIntent.hasExtra("selected_date")) {
			
        	Date date = new Date();
        	
        	int year = cld.get(Calendar.YEAR);
			int month = cld.get(Calendar.MONTH);
			int day = cld.get(Calendar.DATE);
        	
        	try {
        		
        		Calendar cal = Calendar.getInstance();
        		
				date = mSdfDate.parse(mIntent.getStringExtra("selected_date"));
				cal.setTime(date);
				
				year = cal.get(Calendar.YEAR);
				month = cal.get(Calendar.MONTH);
				day = cal.get(Calendar.DATE);
				
			} catch (ParseException e) {
				
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
        	cld.set(year, month, day);
        	calStart.set(year, month, day);
        	calEnd.set(year, month, day);
		}
		
		// all day
		cb_day.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				
				if (isChecked) {
					
					start_date.setText(mSdfDate.format(cld.getTime()));
					start_time.setText("");
					
					end_date.setText(mSdfDate.format(cld.getTime()));
					end_time.setText("");
					
					start_time.setOnClickListener(null);
					end_time.setOnClickListener(null);
					
					Calendar cld = Calendar.getInstance();
					mCldRemind.setTime(cld.getTime());
					cld = null;
					
					mRemindIndex = -1;
					
				} else {		// task with start time and end time
					
					Calendar cal = Calendar.getInstance();
					
					int minute = cal.get(Calendar.MINUTE);
					
					Log.e(TAG, "minute is: "+ minute);
					
					if (minute>=0 && minute<30) {
						
						calStart.set(Calendar.MINUTE, 30);
					}
					
					if (minute>=30 && minute<=59) {
						
						cal.add(Calendar.MINUTE, 60-minute);
						calStart.setTime(cal.getTime());
					}
					
					start_date.setText(mSdfDate.format(calStart.getTime()));
					start_time.setText(mSdfTime.format(calStart.getTime()));
					
					calEnd.setTime(calStart.getTime());
					calEnd.add(Calendar.HOUR_OF_DAY, 1);
					end_date.setText(mSdfDate.format(calEnd.getTime()));
					end_time.setText(mSdfTime.format(calEnd.getTime()));
					
					start_time.setOnClickListener(NewTaskAct.this);
					end_time.setOnClickListener(NewTaskAct.this);
				}
				
				((TextView) findViewById(R.id.tv_remind)).setText("");
			}
		});
		
		// start time and end time
		if (cb_day.isChecked())	{	// all day task
			
			start_date.setText(mSdfDate.format(calStart.getTime()));
			start_time.setText("");	
			
			end_date.setText(mSdfDate.format(calStart.getTime()));
			end_time.setText("");
			
			start_date.setOnClickListener(this);
			end_date.setOnClickListener(this);
			
		} else {		// specific time task
			
			int minute = cld.get(Calendar.MINUTE);
			
			if (minute>=0 && minute<30) {
				
				calStart.set(Calendar.MINUTE, 30);
			}
			
			if (minute>=30 && minute<=59) {
				
				calStart.add(Calendar.MINUTE, 60-minute);
			}
			
			start_date.setText(mSdfDate.format(calStart.getTime()));
			start_time.setText(mSdfTime.format(calStart.getTime()));
			
			calEnd.set(Calendar.HOUR_OF_DAY, calStart.get(Calendar.HOUR_OF_DAY)+1);
			end_date.setText(mSdfDate.format(calEnd.getTime()));
			end_time.setText(mSdfTime.format(calEnd.getTime()));
			
			start_date.setOnClickListener(this);
			start_time.setOnClickListener(this);
			end_date.setOnClickListener(this);
			end_time.setOnClickListener(this);
		}
		
		// repeat event
		((TextView) mAgenda.findViewById(R.id.tv_repeat)).setText("");
		ll_repeat.setOnClickListener(this);
	}

	private void handleEvent() {
		
		ll_list.setOnClickListener(this);
		
		ll_prior.setOnClickListener(this);
		
		/**
		 * Save a task
		 */
		((Button) findViewById(R.id.btn_save_task)).setOnClickListener(this);

		/*OnClickListener ocl = new Button.OnClickListener() {
			public void onClick(View v) {
				Intent itt = new Intent();
				setResult(0, itt);
				finish();
			}
		};*/
		
		((Button) findViewById(R.id.btn_cal_task)).setOnClickListener(this);
		
		ImageButton btnReturn = (ImageButton) findViewById(R.id.btn_return);
		btnReturn.setOnClickListener(this);
		btnReturn.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					
					v.setBackgroundResource(R.drawable.back_pressed);
					
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					
					v.setBackgroundResource(R.drawable.back);
				}

				return false;
			}
			
		});

		EditText et_title = (EditText) findViewById(R.id.et_task);
		et_title.addTextChangedListener(this);
		
		if (mIsAgenda) {
			
			((LinearLayout) findViewById(R.id.ll_repeat)).setOnClickListener(this);
		}
		
		((LinearLayout) findViewById(R.id.ll_context)).setOnClickListener(this);
		((LinearLayout) findViewById(R.id.ll_project)).setOnClickListener(this);
		((LinearLayout) findViewById(R.id.ll_position)).setOnClickListener(this);
		((LinearLayout) findViewById(R.id.ll_tag)).setOnClickListener(this);
		
		// remind event
		ll_remind.setOnClickListener(this);
		
	}
	
	private void saveTask() {
		
		String new_task, task_note, task_list;
		String task_ctt = "", task_prj = "", task_pos = "";
		String repeat = "";
		String remind, strPrior, tag;

		Calendar cldCur = Calendar.getInstance();	// time when save a task
		cldCur.clear(Calendar.MILLISECOND);
		cldCur.set(Calendar.SECOND, 0);
		
		/*
		 * Collect task data
		 */
		// first group
		new_task = et_task.getText().toString();
		task_note = et_note.getText().toString();
		task_list = ((TextView) findViewById(R.id.tv_list)).getText().toString();

		// second group
		task_ctt = ((TextView) findViewById(R.id.tv_context)).getText().toString();
		if (task_ctt.length() == 0)
			task_ctt = ga.getContexts().get(0);
		task_prj = ((TextView) findViewById(R.id.tv_project)).getText().toString();
		if (task_prj.length() == 0)
			task_prj = ga.getProjects().get(0);
		
		Position position = ga.getPositions().get(mPosIndex);
		task_pos = position.getPlace();
		if (ga.mPosRemind && mPosIndex>0) {
			
			mLocAlert = true;
		}
		

		// third group
		if (mIsAgenda) {		// this task is scheduled
			
			Calendar cldS = (Calendar) calStart.clone();
//			Calendar cldC = Calendar.getInstance();
			
			cldS.set(Calendar.SECOND, 0);
			cldS.clear(Calendar.MILLISECOND);
			
			if (cb_day.isChecked()) {		// all day task
				
				cldCur.set(Calendar.HOUR_OF_DAY, 0);
				cldS.set(Calendar.HOUR_OF_DAY, 0);
				
				cldCur.set(Calendar.MINUTE, 0);
				cldS.set(Calendar.MINUTE, 0);
			}
			
			Log.e(TAG, "cldCur: " + mSdf.format(cldCur.getTime()));
			Log.e(TAG, "cldS: " + mSdf.format(cldS.getTime()));
			
			if (cldS.before(cldCur)) {
				
				Toast.makeText(NewTaskAct.this,
						getString(R.string.msg_save),
						Toast.LENGTH_LONG)
					.show();
				
				calStart.setTime(Calendar.getInstance().getTime());
				((TextView) findViewById(R.id.start_date))
					.setText(mSdfDate.format(calStart.getTime()));
				
				if (!cb_day.isChecked()) {
					
					((TextView) findViewById(R.id.start_time))
						.setText(mSdfTime.format(calStart.getTime()));
				}
				
				return;
			}
			
			// repeat
			repeat = ((TextView) findViewById(R.id.tv_repeat)).getText().toString();
			
			Log.e(TAG, "repeat string: "+ repeat);
			
		}	// end mIsAgenda
		
		// remind
		remind = ((TextView) findViewById(R.id.tv_remind)).getText().toString();
		if (remind.length() > 0) {
			
			mTimeRemind = true;
			
			mCldRemind.clear(Calendar.MILLISECOND);
			mCldRemind.set(Calendar.SECOND, 0);
			
			if (mCldRemind.before(cldCur)) {
				
				Toast.makeText(NewTaskAct.this,
						getString(R.string.msg_remind),
						Toast.LENGTH_LONG)
					.show();
				
				mCldRemind.setTime(cldCur.getTime());
				((TextView) findViewById(R.id.tv_remind)).setText("");
				
				return;
			}
			
		}
		
		// fourth grouop
		strPrior = ((TextView) findViewById(R.id.tv_prior)).getText().toString();
		tag = ((TextView) findViewById(R.id.tv_tag)).getText().toString();		// String array
		
		/*
		 * New Task to be inserted
		 */
		mNewTask = new TaskItem(new_task, task_note, task_list);

		mNewTask.setContext(task_ctt);
		mNewTask.setProject(task_prj);
		mNewTask.setPosition(task_pos);
		
		if (mIsAgenda) {
			
			mNewTask.setAllDay(cb_day.isChecked());
			mNewTask.setStartTime(mSdf.format(calStart.getTime()));
			mNewTask.setEndTime(mSdf.format(calEnd.getTime()));
			mNewTask.setRepeat(repeat);
			
			Log.e(TAG, "start time is: " + mSdf.format(calStart.getTime()));
			
		} else {
			
			mNewTask.setAllDay(true);		// no agenda, default all day
			mNewTask.setStartTime("");
			mNewTask.setEndTime("");
			mNewTask.setRepeat("");
		}
		
		mNewTask.setRemind(remind);
		
		mNewTask.setPrior(strPrior);
		
		mNewTask.setTags(tag);		// string array split by ","
		
		if (isEdit) {
			
			TaskItem task = ga.getDbta().getTaskItem(mRowId);
			
			mNewTask.setCompletedStatus(task.getCompletedStatus());
			
		} else {
			
			mNewTask.setCompletedStatus(C.TASK.UNCOMPLETED);
		}
		
		mNewTask.setCreated(mSdf.format((Calendar.getInstance()).getTime()));
		
		/*Log.e("NEW TASK", new_task+" "+task_note+" "+task_list
				+" "+task_ctt+" "+task_prj+" "+task_pos
				+" "+cb_day.isChecked()+" "+stDate+" "+stTime
				+" "+etDate+" "+etTime+" "
				+repeat+" "+remind+" "+prior+" "+tag+" "+sdf.format(curTime));*/
		
		
		if (!isEdit) {
			
    		// count + mNumOfTasks
    		int count = (Integer) ga.lists.get(mListIndex).get("item_count");
    		ga.lists.get(mListIndex).put("item_count", count+mNumOfTasks);
    		
    		SharedPreferences prefs = getSharedPreferences(GTDApp.strList, GTDApp.MODE);
    		Editor editor = prefs.edit();
    		
    		editor.putInt("List_count["+mListIndex+"]", count+mNumOfTasks);
    		editor.commit();
		}
		
		
		// insert tasks into table
		mID.clear();
		mRmd.clear();
		
		if (isEdit)	{	// edit existing task
			
			Log.e(TAG, "saving edit task: " + mRowId);
			
			ga.getDbta().updateTask(mRowId, mNewTask);
			
			if (mTimeRemind || mLocAlert) {
				
    			mID.add(mRowId);
    			mRmd.add(mCldRemind);
			}
			
			Log.e(TAG, "task has been updated!");
			
		} else {		// a new task
			
			Calendar cldStart = (Calendar) calStart.clone();
			Calendar cldEnd = (Calendar) calEnd.clone();
			Calendar cldRemind = (Calendar) mCldRemind.clone();
			
			if (mCalType == -1)	{ 		// no repeat task
				
				ga.getDbta().insertTask(mNewTask);
//				cld.setTime(mCldRemind.getTime());
				
				if (mTimeRemind || mLocAlert) {
					
    				mID.add(ga.getDbta().getLastRowId());
    				mRmd.add(cldRemind);
				}
				
				Log.e(TAG, "single task has been inserted!");
				
			} else {		// repeated agenda tasks
				
				Calendar cal = (Calendar) cldRemind.clone();
				
				if (mRepeatType == 3) {		// workday
					
					ga.getDbta().insertTask(mNewTask);
					
					if (mTimeRemind || mLocAlert) {
						
						mID.add(ga.getDbta().getLastRowId());
						mRmd.add(cal);
					}
					
					mNumOfTasks--;
					
					do {
						
						cldStart.add(Calendar.DAY_OF_YEAR, 1);
						cldEnd.add(Calendar.DAY_OF_YEAR, 1);
						cldRemind.add(Calendar.DAY_OF_WEEK, 1);
						
						if (cldStart.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY
								|| cldStart.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) {
							
							continue;
						}
						
						if (cb_day.isChecked())	{	// all day
							
							cldStart.set(Calendar.HOUR_OF_DAY,0);
							cldStart.set(Calendar.MINUTE,0);
							cldStart.set(Calendar.SECOND,0);
							
							cldEnd.set(Calendar.HOUR_OF_DAY,23);
							cldEnd.set(Calendar.MINUTE,59);
							cldEnd.set(Calendar.SECOND,59);
						}
						
						mNewTask.setStartTime(mSdf.format(cldStart.getTime()));
						mNewTask.setEndTime(mSdf.format(cldEnd.getTime()));
						mNewTask.setRemind(mSdf.format(cldRemind.getTime()));
						
						ga.getDbta().insertTask(mNewTask);
						
						if (mTimeRemind || mLocAlert) {
							
    						mID.add(ga.getDbta().getLastRowId());
    						
    						cal = Calendar.getInstance();
    						cal.setTime(cldRemind.getTime());
    						mRmd.add(cal);
						}
						
						mNumOfTasks--;
						
					} while (mNumOfTasks > 0);
					
				} else {		// day, week, month, and year
					
					ga.getDbta().insertTask(mNewTask);
					
					if (mTimeRemind || mLocAlert) {
						
    					mID.add(ga.getDbta().getLastRowId());
    					mRmd.add(cal);
					}
					
					mNumOfTasks--;
					
					do {
						
						if (cb_day.isChecked())	{	// all day
							
							cldStart.set(Calendar.HOUR_OF_DAY,0);
							cldStart.set(Calendar.MINUTE,0);
							cldStart.set(Calendar.SECOND,0);
							
							cldEnd.set(Calendar.HOUR_OF_DAY,23);
							cldEnd.set(Calendar.MINUTE,59);
							cldEnd.set(Calendar.SECOND,59);
						}
						
						cldStart.add(mCalType, 1);
						cldEnd.add(mCalType, 1);
						cldRemind.add(mCalType, 1);
						
						cldStart.set(Calendar.SECOND, 0);
						calEnd.set(Calendar.SECOND, 0);
						
						cldStart.clear(Calendar.MILLISECOND);
						calEnd.clear(Calendar.MILLISECOND);
						
						if (cldStart.before(calEnd)) {		// overlapped repeated task
							
							Toast.makeText(NewTaskAct.this,
									getString(R.string.msg_repeat_overlap),
									Toast.LENGTH_LONG)
								.show();
							
							Log.e(TAG, "cldStart: " + mSdf.format(cldStart.getTime()));
							Log.e(TAG, "calEnd: " + mSdf.format(cldEnd.getTime()));
							
							mCalType = -1;	// set to no repeat
							((TextView) findViewById(R.id.tv_repeat))
								.setText(getString(R.string.no_repeat));
							
							return;
						}
						
						// Set subsequent tasks
						mNewTask.setStartTime(mSdf.format(cldStart.getTime()));
						mNewTask.setEndTime(mSdf.format(cldEnd.getTime()));
						mNewTask.setRemind(mSdf.format(cldRemind.getTime()));
						
						ga.getDbta().insertTask(mNewTask);
						
						if (mTimeRemind || mLocAlert) {
							
    						mID.add(ga.getDbta().getLastRowId());
    						
    						cal = (Calendar) cldRemind.clone();
    						mRmd.add(cal);
    						
//    						Log.e(TAG, "cldRemind: " + mSdf.format(cldRemind.getTime()));
						}
						
						mNumOfTasks--;
						
					} while (mNumOfTasks > 0);
				}
				
			}
		}
		
		// bind activity to service if alarm is set
		if (mTimeRemind || mLocAlert) {
			
    		Intent i = new Intent(NewTaskAct.this, DWTService.class);
    		i.putExtra("position", position);
    		bindService(i, this, BIND_AUTO_CREATE);
		}
		
		// finish current activity
		setResult(RESULT_OK, new Intent());
		finish();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		AlertDialog.Builder builder;
		final String[] items;
		Intent itt = null;
		Bundle bd = new Bundle();
//		int tag = (Integer) v.getTag();
		
		switch (v.getId()) {
		
			case R.id.ll_list:
				
				/*ArrayList<String> als = new ArrayList<String>();
				ArrayList<ListItem> al = ga.getListItems();
				
				for (int i=0; i<al.size(); i++)
					als.add(al.get(i).getListName());
				items = (String[]) als.toArray(new String[als.size()]);*/
				items = ga.mList;
				
				builder = new AlertDialog.Builder(NewTaskAct.this);
				
				builder.setTitle(getString(R.string.sel_list));
				
				builder.setSingleChoiceItems(items, mListIndex,
						new DialogInterface.OnClickListener() {
					
				    public void onClick(DialogInterface dialog, int item) {
				    	
				    	String str = items[item];
				    	mListIndex = item;
				    	((TextView) findViewById(R.id.tv_list)).setText(str);
				    	
				    	LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT);
						lp.setMargins(10, 10, 10, 0);
				    	
				    	if (item == GTDApp.AGENDA) {
				    		
				    		LinearLayout sv = (LinearLayout) findViewById(R.id.ll_in_scroll);
				    		
				    		if (!mIsAgenda) {
				    			
					            sv.addView(mAgenda, 2, lp);
					            
					            initAgenda();
					            
					            mIsAgenda = true;
				    		}
				    		
				    	} else {
				    		
				    		if (mIsAgenda) {
				    			
//				    			LinearLayout toRemoved = ((LinearLayout) mAgenda.findViewById(R.id.ll_agd));
					    		
				    			if (mAgenda != null) {
				    				
						    		ViewGroup vg = (ViewGroup) mAgenda.getParent();
						    		vg.removeView(mAgenda);
						    		
						    		mIsAgenda = false;
					    		}
				    			
				    		}
				    		
				    	}
				    	
				    	dialog.dismiss();
				    }
				});
				builder.show();
				
				break;
				
			case R.id.ll_context:
				
				bd.putInt("pos", contextPos);
				bd.putInt("view_code", C.TASK.CONTEXT);
				bd.putString("view_name", getString(R.string.context));
				
				itt = new Intent(NewTaskAct.this, ViewAct.class);
				
				itt.putExtras(bd);
				startActivityForResult(itt, 0);
				
				break;
				
			case R.id.ll_project:
				
				bd.putInt("pos", projectPos);
				bd.putInt("view_code", C.TASK.PROJECT);
				bd.putString("view_name", getString(R.string.project));
				
				itt = new Intent(NewTaskAct.this, ViewAct.class);
				
				itt.putExtras(bd);
				startActivityForResult(itt, 0);
				
				break;
				
			case R.id.ll_position:
				
				builder = new AlertDialog.Builder(NewTaskAct.this);
				builder.setTitle(getString(R.string.sel_pos));
				
				ArrayList<Position> position = ga.getPositions();
				items = new String[position.size()];
				for (int i=0; i<position.size(); i++) {
					
					items[i] = position.get(i).getPlace();
				}
				
				builder.setSingleChoiceItems(items, mPosIndex, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						mPosIndex = which;
						((TextView) findViewById(R.id.tv_position)).setText(items[which]);
						
						dialog.dismiss();
					}
					
				});
				
				builder.show();
				
				
				break;
				
			case R.id.start_date:
				
				currentView = start_date;
				showDialog(DATE_DIALOG);
				
				break;
				
			case R.id.start_time:
				currentView = start_time;
				showDialog(TIME_DIALOG);
				
				break;
				
			case R.id.end_date:
				
				currentView = end_date;
				showDialog(DATE_DIALOG);
				
				break;
				
			case R.id.end_time:
				
				currentView = end_time;
				showDialog(TIME_DIALOG);
				
				break;
				
			case R.id.ll_repeat:
				
				itt = new Intent(NewTaskAct.this, RepeatAct.class);
				
				itt.putExtra("init_date", calStart);
				
				startActivityForResult(itt, RepeatAct.RESULT_REPEAT);
				
				break;
				
			case R.id.ll_remind:
				
				if (mIsAgenda
						&& !((CheckBox) findViewById(R.id.cb_day)).isChecked()) {
					
					builder = new AlertDialog.Builder(NewTaskAct.this);
					builder.setTitle(getString(R.string.remind_title));
					
					items = (String[]) ga.remind.toArray(new String[ga.remind.size()]);
					builder.setSingleChoiceItems(items, mRemindIndex,
							new DialogInterface.OnClickListener() {
						
					    public void onClick(DialogInterface dialog, int item) {
					    	
					    	mRemindIndex = item;
					    	
					    	String str = items[item];
					    	((TextView) findViewById(R.id.tv_remind)).setText(str);
					    	
					    	Date startTime = calStart.getTime();
					    	mCldRemind.setTime(startTime);
					    	switch (item) {
					    	
						    	case 0:		// task starts
//						    		mCldRemind.setTime(startTime);
						    		break;
						    		
						    	case 1:		// 10 minutes in advance
						    		mCldRemind.add(Calendar.MINUTE, -10);
						    		break;
						    		
						    	case 2:		// 30 minutes in advance
						    		mCldRemind.add(Calendar.MINUTE, -30);
						    		break;
						    		
						    	case 3:		// 1 hour in advance
						    		mCldRemind.add(Calendar.HOUR_OF_DAY, -1);
						    		break;
						    		
						    	case 4:		// 2 hour in advance
						    		mCldRemind.add(Calendar.HOUR_OF_DAY, -2);
						    		break;
						    		
					    		default:
					    			break;
					    	}
					    	
					    	dialog.dismiss();
					    }
					});
					
					builder.show();
					
				} else {
					
					itt = new Intent(NewTaskAct.this, RemindAct.class);
					
					if (mTimeRemind) {
						
						itt.putExtra("time", mCldRemind);
//						itt.putExtra("is_set_remind", mTimeRemind);
					}
					
					startActivityForResult(itt, 0);
				}
				
				break;
				
			case R.id.ll_prior:
				
				items = (String[]) ga.prior.toArray(new String[ga.prior.size()]);
				
				builder = new AlertDialog.Builder(NewTaskAct.this);
				builder.setTitle(getString(R.string.prior_title));
				builder.setSingleChoiceItems(items, priorPos,
						new DialogInterface.OnClickListener() {
					
				    public void onClick(DialogInterface dialog, int item) {
//				        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				    	String str = items[item];
				    	priorPos = item;
				    	((TextView) findViewById(R.id.tv_prior)).setText(str);
				    	dialog.dismiss();
				    }
				    
				});
				
				builder.show();
				
				break;
				
			case R.id.ll_tag:
				
				/*bd.putInt("tag_count", mTags.size());
				bd.putIntegerArrayList("selected", mTags);
				bd.putInt("view_code", C.TASK.TAG);
				bd.putString("view_name", getString(R.string.tag));*/
				
				itt = new Intent(NewTaskAct.this, TagAct.class);
				
				itt.putExtra("tag_count", mTags.size());
//				itt.putExtra("view_code", C.TASK.TAG);
//				itt.putExtra("view_name", getString(R.string.tag));
				itt.putIntegerArrayListExtra("selected", mTags);
				
//				itt.putExtras(bd);
				
				startActivityForResult(itt, 0);
				
				break;
				
			case R.id.btn_save_task:
				
				saveTask();
				
				break;
				
			case R.id.btn_return:
			case R.id.btn_cal_task:
				
				finish();
				
				break;
				
			default:
				break;
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);

		Bundle bd = null;
		
		Log.i(TAG, "onActivityResult method is called!");

		if (data != null)
			bd = data.getExtras();
		
		switch (resultCode) {
		
			case RESULT_OK:
				
				String str = bd.getString("selected");
				int viewCode = bd.getInt("code");
	
				switch (viewCode) {
				
    				case C.TASK.CONTEXT: // context
    					
    					contextPos = bd.getInt("pos");
    						
    					((TextView) findViewById(R.id.tv_context)).setText(str);
    					
    					break;
    					
    				case C.TASK.PROJECT: // project
    					
    					projectPos = bd.getInt("pos");
    					
    					((TextView) findViewById(R.id.tv_project)).setText(str);
    					
    					break;
    					
    				/*case C.TASK.POSITION: // position
    					
    					positionPos = bd.getInt("pos");
    					if (positionPos > 0)
    						((TextView) findViewById(R.id.tv_position)).setText(str);
    					break;*/
    					
    				default:
    					break;
				}
				
				break;
				
			case RESULT_CANCELED: // press back button
				
				Log.e(TAG, "you return here!");
				
				break;
				
			case TagAct.RESULT_TAG:
				
//				Bundle bd1 = data.getExtras();
				int size = data.getIntExtra("tag_count", -1);
				
				mTags.clear();
				mTags = data.getIntegerArrayListExtra("selected");
				
				if (size > 0) {
					
					String rst = "";
					
					if (size >= 2) {
						
						for (int i=0; i<size-1; i++) {
							
							rst += ga.getTags().get(mTags.get(i).intValue()) + ", ";
						}
						
					}
					rst += ga.getTags().get(mTags.get(size - 1).intValue());
					
					((TextView) findViewById(R.id.tv_tag)).setText(rst);
					
				} else {
					
					((TextView) findViewById(R.id.tv_tag)).setText("");
				}
				
				break;
				
			case TagAct.TAG_CANCELED:
				
				mTags.clear();
				mTags = data.getIntegerArrayListExtra("selected");
				
				break;
				
			case RepeatAct.RESULT_REPEAT:
				
				Log.e(TAG, "repeat result!");
				
				handleRepeat(data);
				
				break;
				
			case RemindAct.RESULT_REMIND:
				
//				str = bd.getString("time");
				mCldRemind = (Calendar) data.getSerializableExtra("time");
				
//				remindTime = str;
				((TextView) findViewById(R.id.tv_remind)).setText(mSdf.format(mCldRemind.getTime()));
				
				break;
				
			default:
				break;
		}
	}
	
	private void handleRepeat(Intent intent) {
		
		Calendar cld = (Calendar) calStart.clone();
		TextView tv = (TextView) findViewById(R.id.tv_repeat);
		
		String summary = intent.getStringExtra("repeat_summary");
		tv.setText(summary);
		
		mRepeatType = intent.getIntExtra("repeat_type", -1);
		switch (mRepeatType) {
		
			case 0:			// no repeat
				break;
				
			case 1:			// day
				mCalType = Calendar.DAY_OF_YEAR;
				break;
				
			case 2:			// week
				mCalType = Calendar.WEEK_OF_YEAR;
				break;
				
			case 3:			// workday
				mCalType = Calendar.DAY_OF_YEAR;
				break;
				
			case 4:			// month
				mCalType = Calendar.MONTH;
				break;
				
			case 5:			// year
				mCalType = Calendar.YEAR;
				break;
				
			default:
				
				Log.e(TAG, "invalid repeat type!");
				
				break;
		}
		
		int id = intent.getIntExtra("repeat_end", R.id.rb_never);
		switch (id) {
		
			case R.id.rb_never:		// repeat forever
				
				mNumOfTasks = C.TASK.MAX_REPEAT;
				
				break;
				
			case R.id.rb_times:		// repeat a specific times
				
				mNumOfTasks = intent.getIntExtra("repeat_times", 5);
				
				break;
				
			case R.id.rb_until:		// repeat until some day
				
				Calendar cldUntil = (Calendar) intent.getSerializableExtra("repeat_until");
				
				Log.e(TAG, "repeat type: " + mRepeatType);
				
				switch (mRepeatType) {
				
					case 0:			// no repeat
						
						break;
						
					case 1:			// day
						
						mNumOfTasks = Utils.getDaysBetween(cld, cldUntil)+1;
						
						break;
						
					case 2:			// week
						
						mNumOfTasks = Utils.getWeeks(cld, cldUntil)+1;
						
						break;
						
					case 3:			// workday
						
						mNumOfTasks = Utils.getWorkingDays(cld, cldUntil)+1;
						
						break;
						
					case 4:			// month
						
						mNumOfTasks = Utils.getMonths(cld, cldUntil)+1;
						
						break;
						
					case 5:			// year
						
						mNumOfTasks = Utils.getYears(cld, cldUntil)+1;
						
						break;
						
					default:
						break;
				}
				
				break;
			
			default:
				break;
		}
		
		Log.e(TAG, "number of repeats: " + mNumOfTasks);
		
	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		// TODO Auto-generated method stub
		
		Calendar cldC, cldS, cldE;
		
		cldC = Calendar.getInstance();
		cldS = (Calendar) calStart.clone();
		cldE = (Calendar) calEnd.clone();
		
		cldC.set(Calendar.SECOND, 0);
		cldS.set(Calendar.SECOND, 0);
		cldE.set(Calendar.SECOND, 0);
		
		cldC.clear(Calendar.MILLISECOND);
		cldS.clear(Calendar.MILLISECOND);
		cldE.clear(Calendar.MILLISECOND);
		
		switch (currentView.getId()) {
		
			case R.id.start_date:
				
				cldS.set(Calendar.YEAR, year);
				cldS.set(Calendar.MONTH, monthOfYear);
				cldS.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				
				if (cb_day.isChecked()) {
					
					cldC.set(Calendar.HOUR_OF_DAY, 0);
					cldS.set(Calendar.HOUR_OF_DAY, 0);
					cldE.set(Calendar.HOUR_OF_DAY, 0);
					
					cldC.set(Calendar.MINUTE, 0);
					cldS.set(Calendar.MINUTE, 0);
					cldE.set(Calendar.MINUTE, 0);
				}
					
				if (cldS.before(cldC)) {
					
					Toast.makeText(NewTaskAct.this,
							getString(R.string.msg_start), Toast.LENGTH_LONG)
						.show();
					
					currentView.setText(mSdfDate.format(calStart.getTime()));
					
					return;
				}
				
				if (cldS.after(cldE)) {
					
					Toast.makeText(NewTaskAct.this,
							R.string.msg_start_end,
							Toast.LENGTH_LONG)
						.show();
					
					currentView.setText(mSdfDate.format(calStart.getTime()));
					
					return;
				}
				
				calStart.setTime(cldS.getTime());
				currentView.setText(mSdfDate.format(calStart.getTime()));
				
				break;
				
			case R.id.end_date:
				
				cldE.set(Calendar.YEAR, year);
				cldE.set(Calendar.MONTH, monthOfYear);
				cldE.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				
				if (cb_day.isChecked()) {
					
					cldS.set(Calendar.HOUR_OF_DAY, 0);
					cldE.set(Calendar.HOUR_OF_DAY, 0);
					
					cldS.set(Calendar.MINUTE, 0);
					cldE.set(Calendar.MINUTE, 0);
				}
					
				if (cldS.after(cldE)) {
					
					Toast.makeText(NewTaskAct.this,
							getString(R.string.msg_end_start),
							Toast.LENGTH_LONG)
						.show();
					
					currentView.setText(mSdfDate.format(calEnd.getTime()));
					
					return;
				}
				
				calEnd.setTime(cldE.getTime());
				currentView.setText(mSdfDate.format(calEnd.getTime()));
				
				break;
				
			default:
				break;
		}
		
	}

	@Override
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		
		Calendar cldC, cldS, cldE;
		
		cldC = Calendar.getInstance();
		cldS = (Calendar) calStart.clone();
		cldE = (Calendar) calEnd.clone();
		
		cldC.set(Calendar.SECOND, 0);
		cldS.set(Calendar.SECOND, 0);
		cldE.set(Calendar.SECOND, 0);
		
		cldC.clear(Calendar.MILLISECOND);
		cldS.clear(Calendar.MILLISECOND);
		cldE.clear(Calendar.MILLISECOND);
		
		switch (currentView.getId()) {
		
			case R.id.start_time:
				
				cldS.set(Calendar.HOUR_OF_DAY, hourOfDay);
				cldS.set(Calendar.MINUTE, minute);
				
				if (cldS.before(cldC)) {
					
					Toast.makeText(NewTaskAct.this,
							getString(R.string.msg_start_time), Toast.LENGTH_LONG)
						.show();
					
				
					currentView.setText(mSdfTime.format(calStart.getTime()));
					
					return;
				}
				
				if (cldS.after(cldE)) {
					
					Toast.makeText(NewTaskAct.this,
							getString(R.string.msg_start_end_time),
							Toast.LENGTH_LONG)
						.show();
					
					currentView.setText(mSdfTime.format(calStart.getTime()));
					
					return;
				}
				
				calStart.setTime(cldS.getTime());
				currentView.setText(mSdfTime.format(calStart.getTime()));
				
				break;
				
			case R.id.end_time:
				
				cldE.set(Calendar.HOUR_OF_DAY, hourOfDay);
				cldE.set(Calendar.MINUTE, minute);
				
				if (cldE.before(cldS)) {
					
					Toast.makeText(NewTaskAct.this,
							getString(R.string.msg_end_start_time),
							Toast.LENGTH_LONG)
						.show();
					
					currentView.setText(mSdfTime.format(calEnd.getTime()));
					
					return;
				}
				
				calEnd.setTime(cldE.getTime());
				currentView.setText(mSdfTime.format(calEnd.getTime()));
				
				break;
				
			default:
				break;
		}
	}

	/*@Override
	public void run() {
		// TODO Auto-generated method stub
		
		Intent intent = new Intent("com.android.dwt.NotificationService");
		
		intent.putExtra("id", C.TASK.TIME_NOTIFY);
		intent.putExtra("task", mNewTask);
		
		NewTaskAct.this.startService(intent);
	}*/

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
		if (s.length() > 0) {
			
			((Button) findViewById(R.id.btn_save_task)).setEnabled(true);
			
		} else {
			
			((Button) findViewById(R.id.btn_save_task)).setEnabled(false);
		}
		
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		// TODO Auto-generated method stub
		
		Log.e(TAG, "bind successfully!");
		
		MyBinder binder = (MyBinder) service;
        mService = binder.getService();
        mBound = true;
        	
    	// Set location alert
    	if (mLocAlert) {
    		
    		mService.setTaskID(mID);
        	
        	Position position = ga.getPositions().get(mPosIndex);
        	mService.setTaskLocationAlert(position);
    	}
    	
    	// set remind
    	if (mTimeRemind) {
    		
        	if (isEdit) {		// edit task
            	
        		Calendar cld = Calendar.getInstance();
        		
        		cld.set(Calendar.SECOND, 0);
        		cld.clear(Calendar.MILLISECOND);
        		
            	if (mOldRemind != null) {
            		
            		mOldRemind.set(Calendar.SECOND, 0);
            		mOldRemind.clear(Calendar.MILLISECOND);
            		
            		if (mOldRemind.after(cld))	{	// remove previous alarm
            			
            			mService.removeSingleAlarm(mRowId);	// the alarm exists in sharedpreferences
            		}
            		
            	}
            		
        		mService.setTaskID(mID);
    			mService.setRemindTime(mRmd);
    			mService.setAlarm();
            	
            } else {		// new task
            	
	        	// send remind time of the current task to background service
		        mService.setTaskID(mID);
				mService.setRemindTime(mRmd);
				mService.setAlarm();
            }
        	
    	}
		
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		
		mService = null;
		mBound = false;
	}
	
}
